<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * https://www.geocms.it/Server/servlet/S3JXServletCall?parameters=method_name%3DGetObject%26callback%3Dscube.geocms.GeoResponse.execute%26id%3D1%26clear%3Dtrue%26query%3D((%255Bsales%255D%253D%255Btrue%255D%2520OR%2520%255Bassistance%255D%253D%255Btrue%255D)%2520AND%2520%255BcountryIsoCode2%255D%253D%255BCN%2520OR%2520cn%255D)%2520AND%2520%255BcountryIsoCode2%255D%253D%255BCN%2520OR%2520cn%255D%26licenza%3Dgeo-maseratispa%26progetto%3DDealerLocator%26lang%3Dzh&encoding=UTF-8
 * 
 * 
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
const BRAND = '玛莎拉蒂';
$db->delete('tDealer', ['sBrand' => '玛莎拉蒂']);
$client = new GuzzleHttp\Client();

$res = $client->get(
    'https://www.geocms.it/Server/servlet/S3JXServletCall?parameters=method_name%3DGetObject%26callback%3Dscube.geocms.GeoResponse.execute%26id%3D1%26clear%3Dtrue%26query%3D((%255Bsales%255D%253D%255Btrue%255D%2520OR%2520%255Bassistance%255D%253D%255Btrue%255D)%2520AND%2520%255BcountryIsoCode2%255D%253D%255BCN%2520OR%2520cn%255D)%2520AND%2520%255BcountryIsoCode2%255D%253D%255BCN%2520OR%2520cn%255D%26licenza%3Dgeo-maseratispa%26progetto%3DDealerLocator%26lang%3Dzh&encoding=UTF-8'
);
$mas = (string)$res->getBody();


//$mas=file_get_contents('a.log');

$mas1=strstr($mas,'{\"C\":\"1\",');

$mas2=strstr($mas1,'","",1));',true);
$mas3=str_replace('\\','',$mas2);

//file_put_contents("b.log",$mas3);die;
$dealers = json_decode($mas3, true);
//var_dump($dealers['L'][0]['O'][1]['G'][0]['P'][0]['y']);die;
//var_dump($dealers['L'][0]['O'][87]['U']);die;
foreach ($dealers['L'][0]['O'] as $item) {

	if(!isset($item['U']['dealername'])&&!isset($item['U']['dagencyname'])){
    	continue;
    }

    $type='';
    if($item['U']['sales']==='true'){
    	$type.='销售,';
    }
    if($item['U']['assistance']==='true'){
    	$type.='救援,';
    }

    if($item['U']['autoBodyShop']==='true'){
    	$type.='授权钣金喷漆服务';
    }
    


    $db->insert('tDealer', [
        'sDealerName' => isset($item['U']['dealername'])?$item['U']['dealername']:$item['U']['dagencyname'],
        'nBrandID' => $item['U']['dealercode'],
        'sBrand' => BRAND,
        'sProvince' => $item['U']['province'],
        'sCity' => $item['U']['city'],
        'sAddress' =>  $item['U']['address'],
        'sSaleCall' => $item['U']['phone'],
        'sLatitude' => $item['G'][0]['P'][0]['y'],
        'sLongitude' => $item['G'][0]['P'][0]['x'],
        'dUpdateTime' => Medoo::raw('now()'),
        'sManufacturer' => BRAND,
        'sRemarks'=>$type,
    ]);
    echo "{$item['D']}完成" . PHP_EOL;
}


echo '爬虫结束' . PHP_EOL;